import useAppStore from "@/store/hooks";
import { Button, Grid, InputLabel, Modal, Typography } from "@mui/material";
import { forwardRef, useImperativeHandle, useState } from "react";
import "./index.scss";
import { observer } from "mobx-react";
import Row from "@components/row";
import useClickAway from "@/hooks/useClickAway";

export interface SettingsModalInstance {
  open: () => void;
  close: () => void;
}

const SettingsModal = observer(
  forwardRef<SettingsModalInstance, { open?: boolean; onClose?: () => void }>(
    (props, ref) => {
      const [open, setOpen] = useState(false);
      useImperativeHandle(
        ref,
        () => ({
          open: () => {
            setOpen(true);
          },
          close: () => {
            setOpen(false);
          },
        }),
        []
      );
      const realOpen = props.open !== undefined ? props.open : open;
      const handleClickAway = () => {
        setOpen(false);
      };
      const clickAwayRef = useClickAway(handleClickAway);
      const store = useAppStore("store");
      const fpsQueue = [1, 10, 30, 60, 90];

      function handleFps() {
        const index = fpsQueue.findIndex((fps) => fps === store.fps);
        const nextIndex = index + 1 === fpsQueue.length ? 0 : index + 1;
        store.setFps(fpsQueue[nextIndex]);
      }

      return (
        <Modal
          open={realOpen}
          onClose={() => {
            props.onClose?.();
          }}
        >
          <div className="settings-view" ref={clickAwayRef}>
            <Grid container>
              <Grid item xs={12}>
                <Row justify="center">
                  <Typography variant="h5">Settings</Typography>
                </Row>
              </Grid>
              <Grid item xs={12}>
                <Row gap={8}>
                  <InputLabel>fps: </InputLabel>
                  <Button
                    onClick={handleFps}
                    variant="contained"
                    color="info"
                    className="fps-btn"
                  >
                    {store.fps}
                  </Button>
                </Row>
              </Grid>
            </Grid>
          </div>
        </Modal>
      );
    }
  )
);

export default SettingsModal;
